﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using RTW.Core.Extensions;
using RTW.Models;
using RTW.Servers;
using RTW.Web.Comm;
using RTW.Web.Models;

namespace RTW.Web.Areas.System.Controllers
{
    [Area("System")]
    public class RoleController : CommController
    {
        private readonly TRoleServer roleServers;
        readonly DepartmentServer departmentServer;
        TUserInfoServer userInfoServer;
        public RoleController()
        {
            roleServers = new TRoleServer();
            departmentServer = new DepartmentServer();
            userInfoServer = new TUserInfoServer();
        }
        public IActionResult UserRole()
        {
            return View();
        }


        public async Task<IActionResult> UserRoleEdit(string DMID, string ID)
        {
            ViewBag.DMID = DMID;
            //IList<TRole> list = await roleServers.GetAsync();
            //List<SelectListItem> listitem = new List<SelectListItem>
            //{
            //    new SelectListItem { Text = "", Value = "" }
            //};
            //foreach (var dep in list)
            //{
            //    listitem.Add(new SelectListItem
            //    {
            //        Text = dep.RName,
            //        Value = dep.ID
            //    });
            //}
            //ViewBag.Roles = listitem;

            TRole role = new TRole();
            //编辑或新增
            if (string.IsNullOrEmpty(ID))
            {

            }
            else
            {
                //修改时回绑字段
                role = await roleServers.GetByOneAsync(m => m.ID == ID);
                ViewBag.DMID = role.DMID;
            }
            return View(role);
        }
        [HttpPost]
        public async Task<IActionResult> UserRoleEdit(string DMID, string ID, TRole role)
        {
            ViewBag.DMID = DMID;
            //IList<TRole> list = await roleServers.GetAsync();
            //List<SelectListItem> listitem = new List<SelectListItem>
            //{
            //    new SelectListItem { Text = "", Value = "" }
            //};
            //foreach (var dep in list)
            //{
            //    listitem.Add(new SelectListItem
            //    {
            //        Text = dep.RName,
            //        Value = dep.ID
            //    });
            //}
            //ViewBag.Roles = listitem;

            try
            {
                if (string.IsNullOrEmpty(ID))
                {
                    //新增
                    role.ID = Guid.NewGuid().ToString("N");
                    // user.OrgID = user.OrgID;//更新父节点ID
                    role.AddTime = DateTime.Now;
                    role.DMID = DMID;
                    await roleServers.InsertAsync(role);


                    AddLog("添加了用户身份（" + role.RName + "）", "用户身份管理", Request.GetAbsoluteUri());
                }
                else
                {
                    //修改
                    // user.Parent_ID = user.Bak2;//更新父节点ID
                    await roleServers.UpdateAsync(role);

                    AddLog("修改了用户身份（" + role.RName + "）", "用户身份管理", Request.GetAbsoluteUri());
                }

            }
            catch (Exception e)
            {
                AddErrLog(e.Message, UserDMID);
                return Json(MsgResult(false));
            }
            return Json(MsgResult(true));
        }

        public IActionResult UserRoleQuanXianEdit()
        {
            return View();
        }

        public async Task<IActionResult> GetDepartmentTreeJson()
        {
            var treelist = await departmentServer.GetDpetTreeList();
            List<JsTreeModel> trelist = new List<JsTreeModel>();

            //定义递归方法
            int GetChildrenModule(List<TDepartment> clist, JsTreeModel jsTree)
            {
                var childrenmodules = clist;
                if (childrenmodules.Count() > 0)
                {
                    jsTree.children = new List<JsTreeModel>();
                    foreach (var cm in childrenmodules)
                    {
                        JsTreeModel cjsTree = new JsTreeModel();
                        cjsTree.id = cm.ID;
                        cjsTree.text = cm.RowIndex + "." + cm.DMName;
                        cjsTree.state = new Dictionary<string, bool>() { { "opened", true } };
                        cjsTree.li_attr = new Dictionary<string, string>() { { "class", "jstree-open" } };
                        cjsTree.a_attr = new Dictionary<string, string>() { { "DMID", cm.ID }, { "onclick", "GetTabData('" + cm.ID + "')" } };
                        GetChildrenModule(cm.DMS, cjsTree);
                        jsTree.children.Add(cjsTree);
                    }
                }
                return childrenmodules.Count();
            }

            //遍历根节点
            foreach (var item in treelist)
            {

                JsTreeModel jsTree = new JsTreeModel();
                jsTree.id = item.ID;
                jsTree.text = item.RowIndex + "." + item.DMName;
                jsTree.state = new Dictionary<string, bool>() { { "opened", true } };
                jsTree.li_attr = new Dictionary<string, string>() { { "class", "jstree-open" } };
                jsTree.a_attr = new Dictionary<string, string>() { { "DMID", item.ID }, { "onclick", "GetTabData('" + item.ID + "')" } };
                GetChildrenModule(item.DMS, jsTree);

                trelist.Add(jsTree);
            }

            return Json(trelist);
        }

        public async Task<IActionResult> GetTabData(string DMID)
        {
            var ulist = await roleServers.GetAsync(m=>m.DMID== DMID);
            return Json(ulist);
        }
        public string GetQX(string Rid)
        {
            string STR = "";
            //string sql = "select * from QX_Menu where Url in (select PageUrl from TMenu  where Bak1 like '%" + Rid + "%' ) ";
            //if (DbHelperSQL.Query(" select count(*) from TMenu where PageUrl='/Instruments.aspx' and  Bak1 like '%" + Rid + "%'").Tables[0].Rows[0][0].ToString() != "0")
            //{
            //    sql += "or url in (select Url from QX_Menu where MenuId in (2,3,4)) "; ;
            //}
            //if (DbHelperSQL.Query(" select count(*) from TMenu where PageUrl='/scan3/index.aspx?action=look' and  Bak1 like '%" + Rid + "%'").Tables[0].Rows[0][0].ToString() != "0")
            //{
            //    sql += "or url in (select Url from QX_Menu where MenuId in (6,7)) "; ;
            //}
            //if (DbHelperSQL.Query(" select count(*) from TMenu where PageUrl='/scan4/index.aspx?action=look' and  Bak1 like '%" + Rid + "%'").Tables[0].Rows[0][0].ToString() != "0")
            //{
            //    sql += "or url in (select Url from QX_Menu where MenuId in (10,11)) "; ;
            //}

            //DataTable dt = DbHelperSQL.Query(sql).Tables[0];


            //if (dt.Rows.Count > 0)
            {
                STR = "&emsp;<a href='javascript:void(0);' title='操作权限' onclick=\"showPage('修改角色操作权限','/Role/UserRoleQuanXianEdit?ID=" + Rid + "',800,640,false)\">权限</a>";
            }
            return STR;
        }
    }
}